!function ($) {

  "use strict"; // jshint ;_;

  $.fn.accsetting = function ( option ) {
	
	this.init = function(){
		debug("calling init of accsetting");
		this.each(function(){
			this.init();
		});
	}
	
    return this.each(function () {
      var $lswraprow = new Array();	
      var $focus = null, i = 0;
      
      $(this).find('.accrow').each(function(){
    	  var $accrow = $(this);
    	  var $accbody = $accrow.find('.accbody');
    	  var $accedit = $accrow.find('.accedit');
    	  var $accicon = $accrow.find('.accaction .accicon'); 
    	  
    	  var $wrapedit = $.extend($accedit, {
    		  accfields: $accedit.find('.accfield')
    		  ,
    		  init: function(){
    			  debug("running init of accedit");
    			  this.accfields.each(function(){
    				 debug("accfields.datainit=" + $(this).data('init'));
    				 $(this).val($(this).data('init')); 
    			  });
    		  }
    	  });
    	  var $wraprow = $.extend($accrow, {
    		  id: i++,
    		  accbody: $accbody,
    		  accedit: $wrapedit,
    		  accicon: $accicon,
    		  init: function(){
    			  debug("running init of accrow");
    			  this.collapse();
    			  this.accedit.init();
    		  },
    		  toggle: function(){
    			  debug('calling toggle for row ' + this.id);
    			  debug('toggle is: ' + $accrow.data('toggle'));
    			  if($accrow.data('toggle')=='on'){
    				  return;
    			  }else{
    				  if($focus){
    					  $focus.collapse();
    				  }
    				  $focus = this;
    				  this.expand();
    			  }
    		  },
    		  collapse: function(){
    			  debug('calling collapse for row ' + this.id);
    			  this.accedit.hide();
    			  this.accedit.init();
    			  this.accbody.show();
    			  $accrow.data('toggle','off');
    			  $accrow.removeClass('accrowfocus');
    		  },
    		  expand: function(){
    			  debug('calling expand for row ' + this.id);
    			  this.accedit.show();
    			  this.accbody.hide();
    			  $accrow.data('toggle','on');
    			  $accrow.addClass('accrowfocus');
    			  debug('setting toggle to on');
    		  }
    	  });
    	  
    	  $wraprow.click(function(){
    		  $wraprow.toggle();
          });
    	  
    	  $wraprow.find('.btn-collapse').click(function(e){
    		  e.stopPropagation();
    		  debug("button collapse is clicked");
    		  $wraprow.collapse();
    	  });
    	  
    	  $lswraprow.push($wraprow);
      });
      /*public method*/
      this.init = function(){
    	  debug("running init of accsetting");
    	  for (var i = 0; i < $lswraprow.length; i++){
    		  $lswraprow[i].init();
    	  }
      }
    });
  }


}(window.jQuery);
